package com.longe.netty.scheduleTaskQueue;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 服务端
 */
public class NettyServer {

    private final static Integer PORT = 9999;

    public static void main(String[] args) {

        //创建 bossGroup 和 workerGroup
        //bossGroup只处理连接请求, workerGroup处理和客户端的业务
        //bossGroup 和 workerGroup 默认的子线程(即NioEventLoop)个数为：cpu核数 * 2
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            //创建服务端的启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置参数
            serverBootstrap.group(bossGroup, workerGroup) //设置两个线程组
                    .channel(NioServerSocketChannel.class) //使用NioServerSocketChannel作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128) //设置线程队列等待连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) //设置保存活动状态连接
                    //.handler() 该 handler对应 bossGroup, 下面的childHandler 对应 workerGroup
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //ChannelInitializer为通道初始化对象
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            //给管道(pipeline)添加处理器
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.err.println("NettyHttpServer is ready......");
            //绑定端口, 启动服务器
            ChannelFuture channelFuture = serverBootstrap.bind(PORT).sync();
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
